/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: UserCoreService
 * Author:   zhouheng
 * Date:     2019/4/16 0:26
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.dubbo.user.provider.services;

import com.dubbo.user.api.IUserCoreService;
import com.dubbo.user.api.constants.Constants;
import com.dubbo.user.api.constants.ResponseCodeEnum;
import com.dubbo.user.api.dto.*;
import com.dubbo.user.provider.dal.entity.User;
import com.dubbo.user.provider.dal.mapper.UserMaper;
import com.dubbo.user.provider.exception.ExceptionUtil;
import com.dubbo.user.provider.exception.ServiceException;
import com.dubbo.user.provider.exception.ValidateException;
import com.dubbo.user.provider.utils.JwtInfo;
import com.dubbo.user.provider.utils.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author zhouheng
 * @create 2019/4/16
 * @since 1.0.0
 */

@Slf4j
@Service("userLoginService")
public class UserCoreService implements IUserCoreService {


    @Autowired
    private UserMaper userMaper;

    @Autowired
    private JwtTokenService jwtTokenService;

    /**
     * @description: 登陆
     * @date: 2019/4/16 8:16
     * @author:zhouheng
     */
    public UserLoginResponse login(UserLoginRequest userLoginRequest) {
        log.info("begin UserCoreService.login,request:【"+userLoginRequest+"】");
        UserLoginResponse response = new UserLoginResponse();

        try{
            beforeValidate(userLoginRequest);
            User user = userMaper.getUserByUserName(userLoginRequest.getUsername());
            if (user == null || !user.getPassword().equals(userLoginRequest.getPassword())){
                response.setCode(ResponseCodeEnum.USER_OR_PASSWORD_ERROR.getCode());
                response.setMsg(ResponseCodeEnum.USER_OR_PASSWORD_ERROR.getMsg());
                return response;
            }

            //todo 判断用户状态
            response.setAvatar(user.getAvatar());
            response.setMobile(user.getMobile());
            response.setRealName(user.getRealname());
            response.setSex(user.getSex());
            //TODO 生成token
            response.setToken(jwtTokenService.generatorToken(new JwtInfo(user.getId().toString())));
            response.setCode(ResponseCodeEnum.SYS_SUCCESS.getCode());
            response.setMsg(ResponseCodeEnum.SYS_SUCCESS.getMsg());


            return response;

        }catch (Exception e){
            // todo
//            ServiceException serviceException = (ServiceException) ExceptionUtil.handlerException4biz(e);
//            response.setCode(serviceException.getErrorCode());
//            response.setMsg(serviceException.getErrorMessage());
        }finally {
            log.info("login response:【"+response+"】");
        }

        return response;
    }

    /**
     * @description: 注册
     * @date: 2019/4/16 8:16
     * @author:zhouheng
     */
    public UserRegisterResponse register(UserRegisterRequest userRegisterRequest) {
        log.info("begin UserCoreService.register,request:【"+userRegisterRequest+"】");
        UserRegisterResponse response = new UserRegisterResponse();
        
        try{
            beforeRegisterValidate(userRegisterRequest);
            User user = new User();
            user.setUsername(userRegisterRequest.getUsername());
            // TODO md5加密
            user.setPassword(userRegisterRequest.getPassword());
            user.setStatus(Constants.FORZEN_USER_STATUS);
            user.setCreateTime(new Date());
            int effectRow = userMaper.insertSelective(user);
            if (effectRow > 0){
                response.setCode(ResponseCodeEnum.SYS_SUCCESS.getCode());
                response.setMsg(ResponseCodeEnum.SYS_SUCCESS.getMsg());
                return  response;
            }
            response.setCode(ResponseCodeEnum.DATA_SAVE_ERROR.getCode());
            response.setMsg(ResponseCodeEnum.DATA_SAVE_ERROR.getMsg());
            return  response;

        }catch (DuplicateKeyException e){
            //TODO 用户名重复
        }catch (Exception e){
            ServiceException serviceException = (ServiceException) ExceptionUtil.handlerException4biz(e);
            response.setCode(serviceException.getErrorCode());
            response.setMsg(serviceException.getErrorMessage());
        }finally {
            log.info("register response:【"+response+"】");
        }

        return response;
    }

    /**
     * @description: 参数校验
     * @date: 2019/4/16 22:43
     * @author:zhouheng
     */
    private void beforeRegisterValidate(UserRegisterRequest request) {
        if(null==request){
            throw new ValidateException("请求对象为空");
        }
        if(StringUtils.isEmpty(request.getUsername())){
            throw new ValidateException("用户名为空");
        }
        if(StringUtils.isEmpty(request.getPassword())){
            throw new ValidateException("密码为空");
        }
        if(StringUtils.isEmpty(request.getMobile())){
            throw new ValidateException("手机号为空");
        }
    }

    /**
     * @description: 鉴权
     * @date: 2019/4/16 8:17
     * @author:zhouheng
     */
    public CheckAuthResponse checkAuth(CheckAuthRequest request) {
        CheckAuthResponse response = new CheckAuthResponse();

        try{
            beforeCheckAuthValidate(request);
            JwtInfo jwtInfo = jwtTokenService.getInfoFromToken(request.getToken());
            response.setUid(jwtInfo.getUid());
            response.setCode(ResponseCodeEnum.SYS_SUCCESS.getCode());
            response.setMsg(ResponseCodeEnum.SYS_SUCCESS.getMsg());
        }catch (ExpiredJwtException e){
            //TODO
            log.error("error",e);
        }catch (SignatureException e){
            log.error("error",e);
        }catch(Exception e){
            ServiceException serviceException=(ServiceException) ExceptionUtil.handlerException4biz(e);
            response.setCode(serviceException.getErrorCode());
            response.setMsg(serviceException.getErrorMessage());
        }finally {
            log.info("checkAuth response:【"+response+"】");
        }

        return response;
    }

    /**
     * @description: 校验传参
     * @date: 2019/4/16 23:35
     * @author:zhouheng
     */
    private void beforeCheckAuthValidate(CheckAuthRequest request) {
        if(null == request){
            throw new ValidateException("请求对象为空");
        }
        if(StringUtils.isEmpty(request.getToken())){
            throw new ValidateException("token信息为空");
        }
    }

    /**
     * @description: 检验传参
     * @date: 2019/4/16 23:35
     * @author:zhouheng
     */
    private void beforeValidate(UserLoginRequest userLoginRequest) {
        if(null == userLoginRequest){
            throw new ValidateException("请求对象为空");
        }
        if(StringUtils.isEmpty(userLoginRequest.getUsername())){
            throw new ValidateException("用户名为空");
        }
        if(StringUtils.isEmpty(userLoginRequest.getPassword())){
            throw new ValidateException("密码为空");
        }
    }
}